﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        private static object m_res1 = new object();
        private static object m_res2 = new object();
        private static int m_count = 0;

        static void Main(string[] args)
        {
            Thread t1 = new Thread(Thread1);
            Thread t2 = new Thread(Thread2);

            t1.Start();
            t2.Start();

            while (true)
            {
                int preCount = m_count;
                Thread.Sleep(0);  // 放弃当前线程的CPU时间片，Windows可能调度其他线程
                if (preCount == m_count)  // 数据没有变化，表明线程没有执行
                {
                    Console.WriteLine("dead lock! count: {0}", m_count);
                }
            }
        }

        private static void Thread1()
        {
            while (true)
            {
                Monitor.Enter(m_res2);  // 先锁 m_res2
                Monitor.Enter(m_res1);  // 再锁 m_res1

                m_count++;

                Monitor.Exit(m_res1);  // 释放锁不存在先后关系
                Monitor.Exit(m_res2);
            }
        }

        private static void Thread2()
        {
            while (true)
            {
                Monitor.Enter(m_res1);  // 先锁 m_res1
                Monitor.Enter(m_res2);

                m_count++;

                Monitor.Exit(m_res1);
                Monitor.Exit(m_res2);
            }
        }
    }
}
